package com.guoby.aspect;

import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by pactera on 2018/5/10.
 */
public class CrosFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String origin = request.getHeader("Origin");
        if (StringUtils.isEmpty(origin))
            origin = "*";

        response.addHeader("Access-Control-Allow-Origin", origin);
        response.addHeader("Access-Control-Allow-Methods", "*");
        // 自定义header需要添加
        String headers = request.getHeader("Access-Control-Request-Headers");
        response.addHeader("Access-Control-Allow-Headers", headers);
        // 3600秒已经，可以不用发预警信息（缓存预警请求）
        response.addHeader("Access-Control-Max-Age", "3600");
        // enable cookie
        response.addHeader("Access-Control-Allow-Credentials", "true");


        filterChain.doFilter(servletRequest, response);
    }

    @Override
    public void destroy() {

    }
}
